package com.suneast.suneaststore.modules.personal.trace;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.suneast.suneaststore.App;
import com.suneast.suneaststore.R;
import com.suneast.suneaststore.app.Latte;
import com.suneast.suneaststore.bean.personal.trace.TraceBean_;
import com.suneast.suneaststore.modules.goodsdetail.GoodsDetailFragment;
import com.suneast.suneaststore.modules.personal.trace.adapter.TraceAdapter;
import com.suneast.suneaststore.bean.personal.trace.TraceAdapterBean;
import com.suneast.suneaststore.bean.personal.trace.TraceBean;
import com.suneast.suneaststore.bean.personal.trace.TraceDateBean;
import com.suneast.suneaststore.modules.personal.trace.event.TraceSelectEvent;
import com.suneast.suneaststore.ui.dialog.CancelConfirmDialog;
import com.suneast.suneaststore.ui.fragments.AbsBaseFragment;
import com.suneast.suneaststore.util.log.LatteLogger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.objectbox.Box;

public class TraceFragment extends AbsBaseFragment implements TraceAdapter.OnItemTraceClickListener, CancelConfirmDialog.ConfirmBtnClickListener {
    private final static int PAGE_SIZE = 5;

    @Override
    public int setLayout() {
        return R.layout.fragment_trace;
    }

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.rv_trace)
    RecyclerView traceRV;
    TraceAdapter traceAdapter;

    @BindView(R.id.refresh_rv_trace)
    SmartRefreshLayout refreshLayout;

    @BindView(R.id.btn_cancel_edit)
    Button cancelEditBtn;

    @BindView(R.id.btn_delete_selected)
    Button deleteSelectedBtn;

    @OnClick({R.id.btn_cancel_edit, R.id.btn_delete_selected})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.btn_cancel_edit: {
                //隐藏 取消按钮和 删除按钮
                cancelEditBtn.setVisibility(View.GONE);
                deleteSelectedBtn.setVisibility(View.GONE);
                // 恢复至不显示 checkbox 的界面
                refreshTrace(false, false);
                //清空已选择List
                selectedBeanList.clear();
            }
            break;
            case R.id.btn_delete_selected: {
                //删除勾选
                for (TraceBean bean : selectedBeanList) {
                    traceBeanBox.remove(bean);
                }
                refreshTrace(true, true);
            }
            break;
        }
    }

    private Box<TraceDateBean> dateBeanBox;
    private Box<TraceBean> traceBeanBox;
    private int curPage = 1;

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        EventBus.getDefault().register(this);
        dateBeanBox = App.getBoxStore().boxFor(TraceDateBean.class);
        traceBeanBox = App.getBoxStore().boxFor(TraceBean.class);

        initToolBar();
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableLoadMore(true);

        refreshLayout.setOnLoadMoreListener((@NonNull RefreshLayout refreshLayout) -> {
            Latte.getHandler().postDelayed(() -> {
                traceAdapter.addData(generateTraceAdapterBeanList(curPage + 1));
                refreshLayout.finishLoadMore();
            }, 800);
        });

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        traceRV.setLayoutManager(linearLayoutManager);
        traceAdapter = new TraceAdapter(R.layout.item_trace, generateTraceAdapterBeanList(curPage));
        traceAdapter.setItemTraceClickListener(this);
        traceRV.setAdapter(traceAdapter);
    }

    private void initToolBar() {
        initDialog();
        toolbar.setNavigationOnClickListener((View v) -> {
            pop();
        });
        //添加菜单
        toolbar.inflateMenu(R.menu.menu_trace);
        // 添加菜单点击事件
        toolbar.setOnMenuItemClickListener((MenuItem item) -> {
            switch (item.getItemId()) {
                case R.id.nav_clear: {
                    //点击清除
                    dialog.show(getFragmentManager(), "clear_trace");
                }
                break;
                case R.id.nav_edit: {
                    //点击编辑
                    if (deleteSelectedBtn.getVisibility() == View.GONE) {
                        selectedBeanList.clear();
                        if (traceAdapter.getData().size() == 0) {
                            Toast.makeText(_mActivity, "没有浏览记录", Toast.LENGTH_SHORT).show();
                            break;
                        }
                        cancelEditBtn.setVisibility(View.VISIBLE);
                        deleteSelectedBtn.setVisibility(View.VISIBLE);
                        refreshTrace(true, false);
                    }
                }
                break;
            }
            return false;
        });
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    CancelConfirmDialog dialog = null;

    private void initDialog() {
        dialog = new CancelConfirmDialog();
        Bundle bundle = new Bundle();
        bundle.putString("content", "确定要清空全部浏览记录?");
        dialog.setArguments(bundle);
        dialog.setListener(this);
    }

    @Override
    public void onItemTraceClick(TraceBean bean) {
        GoodsDetailFragment fragment = new GoodsDetailFragment().withId(bean.getGoodsId());
        start(fragment);
    }

    @Override
    public void onConfirm() {
        dateBeanBox.removeAll();
        traceBeanBox.removeAll();
        traceAdapter.setNewData(new ArrayList<>());
        dialog.dismiss();
    }

    @Override
    public void onCancel() {
        dialog.dismiss();
    }

    private List<TraceAdapterBean> generateTraceAdapterBeanList(int page) {
        List<TraceDateBean> dateBeanList = dateBeanBox.getAll();
        List<TraceDateBean> nullTraceDateList = new ArrayList<>();
        List<TraceAdapterBean> dataList = new ArrayList<>();
        if (page * PAGE_SIZE - dateBeanList.size() > PAGE_SIZE) {
            refreshLayout.setNoMoreData(true);
            return dataList;
        } else {
            curPage = page;
        }
        int length = Math.min(PAGE_SIZE * page, dateBeanList.size());
        for (int i = PAGE_SIZE * (page - 1); i < length; i++) {
            List<TraceBean> traceBeanList = traceBeanBox.query()
                    .equal(TraceBean_.dateStr, dateBeanList.get(i).getDateStr())
                    .build().find();
            LatteLogger.e("test", "size = " + traceBeanList.size());
            if (traceBeanList.size() > 0) {
                dataList.add(new TraceAdapterBean(dateBeanList.get(i).getDateStr(), traceBeanList));
            } else {
                nullTraceDateList.add(dateBeanList.get(i));
            }
        }
        if (nullTraceDateList.size() > 0) {
            for (TraceDateBean bean : nullTraceDateList) {
                dateBeanBox.remove(bean);
            }
        }
        return dataList;
    }

    private void refreshTrace(boolean showCheckBox, boolean fromDB) {
        traceAdapter.setShowCheckBox(showCheckBox);
        List<TraceAdapterBean> newData;
        if (fromDB) {
            refreshLayout.setNoMoreData(false);
            curPage = 1;
            newData = generateTraceAdapterBeanList(curPage);
        } else {
            newData = new ArrayList<>(traceAdapter.getData());
        }
        traceAdapter.setNewData(newData);
    }

    private List<TraceBean> selectedBeanList = new ArrayList<>();

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSelectChanged(TraceSelectEvent event) {
        if (event.isSelect()) {
            selectedBeanList.add(event.getTraceBean());
        } else {
            selectedBeanList.remove(event.getTraceBean());
        }
    }
}
